/*
 * Powered By [rapid-framework]
 * Web Site: http://www.rapid-framework.org.cn
 * Google Code: http://code.google.com/p/rapid-framework/
 * Since 2008 - 2011
 */

package com.tech15.core.service;

import java.util.ArrayList;
import java.util.List;

import javacommon.base.BaseManager;
import javacommon.base.EntityDao;
import javacommon.util.LoginInfo;
import javacommon.util.MD5;
import javacommon.util.org.TreeData;
import javacommon.util.org.TreeUtils;

import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.org.rapid_framework.page.Page;
import cn.org.rapid_framework.util.ObjectUtils;

import com.tech15.core.dao.DeptDao;
import com.tech15.core.dao.GroupDao;
import com.tech15.core.dao.GroupUserDao;
import com.tech15.core.dao.SysUserDao;
import com.tech15.core.dao.SysYgDao;
import com.tech15.core.model.Dept;
import com.tech15.core.model.Group;
import com.tech15.core.model.GroupUser;
import com.tech15.core.model.SysUser;
import com.tech15.core.model.SysYg;
import com.tech15.core.vo.query.SysUserQuery;

/**
 * @author 胡作正 email:zuozhenghu@sina.com
 * @version 1.0
 * @since 1.0
 */

@Service
@Transactional
public class SysUserManager extends BaseManager<SysUser,Long>{

	private SysUserDao sysUserDao;
	private GroupDao groupDao;
	private GroupUserDao groupUserDao;
	private DeptDao deptDao;
	private SysYgDao sysYgDao;
	
	public void setSysYgDao(SysYgDao sysYgDao) {
		this.sysYgDao = sysYgDao;
	}
	public void setDeptDao(DeptDao deptDao) {
		this.deptDao = deptDao;
	}
	public void setGroupUserDao(GroupUserDao groupUserDao) {
		this.groupUserDao = groupUserDao;
	}
	public void setSysUserDao(SysUserDao dao) {
		this.sysUserDao = dao;
	}
	public EntityDao getEntityDao() {
		return this.sysUserDao;
	}
	public void setGroupDao(GroupDao groupDao) {
		this.groupDao = groupDao;
	}
	
	@Transactional(readOnly=true)
	public SysUser getUserById(Long id){
		return sysUserDao.getById(id);
	}
	
	@Transactional(readOnly=true)
	public SysUser getById(Long id){
		SysUser user = (SysUser)getEntityDao().getById(id);
		List<Group> groupList = groupDao.selectGroupByUserid(id);
		user.setGroupList(groupList);
		if(user.getDeptid() != null){
			Dept dept = deptDao.getById(user.getDeptid());
			if(dept != null){
				user.setDeptName(dept.getDeptname());
			}
		}
		
		if(user.getTaskdeptid() != null){
			Dept dept = deptDao.getById(user.getTaskdeptid());
			if(dept != null){
				user.setTaskdeptname(dept.getDeptname());
			}
		}
		
		SysYg yg =sysYgDao.getById(user.getUsername());
		if(yg != null){
			user.setTel(yg.getTel());
			user.setPhone(yg.getPhone());
		}
		return user;
	}
	
	@Transactional(readOnly=true)
	public Page findPage(SysUserQuery query) {
		return sysUserDao.findPage(query);
	}
	
	public boolean saveUser(SysUser user) {
//		判断此用户名是否存在
		boolean mark = sysUserDao.isUnique(user, "username");
		if(!mark){
			return false;
		}else{
			MD5 md5 = new MD5();
			String md_pwd = md5.getMD5ofStr(user.getPassword());
			user.setState("1");
			user.setIsadmin(0);
			user.setPassword(md_pwd);
			sysUserDao.save(user);
			sysUserDao.flush();
			
			/*处理权限组*/
			if(user.getGroupIds() != null && !"".equals(user.getGroupIds())){
				String pridept = user.getGroupIds().replace(" ","");
				String[] pridepts = pridept.split(",");
				List<GroupUser> list = new ArrayList<GroupUser>();
				for(int i=0;i<pridepts.length;i++){
					GroupUser pu = new GroupUser();
					String pgid = pridepts[i].replace("|", ",").split(",")[0];
					pu.setPgid(new Long(pgid));
					pu.setUserid(user.getUserid());
					list.add(pu);
				}
				groupUserDao.getHibernateTemplate().saveOrUpdateAll(list);
			}
			
			return true;
		}
	}
	
	public boolean saveAdminUser(SysUser user) {
//		判断此用户名是否存在
		boolean mark = sysUserDao.isUnique(user, "username");
		if(!mark){
			return false;
		}else{
			MD5 md5 = new MD5();
			String md_pwd = md5.getMD5ofStr(user.getPassword());
			user.setState("1");
			user.setPassword(md_pwd);
			
			if(ObjectUtils.isNotEmpty(user.getDeptid())){
				Dept dept = deptDao.getById(user.getDeptid());
				if(dept != null){
					user.setDeptname(dept.getDeptname());
				}
			}
			sysUserDao.save(user);
			sysUserDao.flush();
			
			/*处理权限组*/
			if(user.getGroupIds() != null && !"".equals(user.getGroupIds())){
				String pridept = user.getGroupIds().replace(" ","");
				String[] pridepts = pridept.split(",");
				List<GroupUser> list = new ArrayList<GroupUser>();
				for(int i=0;i<pridepts.length;i++){
					GroupUser pu = new GroupUser();
					String pgid = pridepts[i].replace("|", ",").split(",")[0];
					pu.setPgid(new Long(pgid));
					pu.setUserid(user.getUserid());
					list.add(pu);
				}
				groupUserDao.getHibernateTemplate().saveOrUpdateAll(list);
			}
			
			return true;
		}
	}
	
	public boolean updateUser(SysUser user) throws DataAccessException{
		boolean mark = sysUserDao.isUnique(user, "username");
		if(!mark){
			return false;
		}else{
			if(ObjectUtils.isNotEmpty(user.getPwd())){
				MD5 md5 = new MD5();
				String md_pwd = md5.getMD5ofStr(user.getPwd());
				user.setPassword(md_pwd);
			}
			if(ObjectUtils.isNotEmpty(user.getDeptid())){
				Dept dept = deptDao.getById(user.getDeptid());
				if(dept != null){
					user.setDeptname(dept.getDeptname());
				}
			}
			sysUserDao.update(user);
			SysYg yg = sysYgDao.getByYgbh(user.getUsername());
			if(yg != null){
				yg.setDeptid(user.getDeptid());
				yg.setDeptname(user.getDeptname());
				sysYgDao.update(yg);
			}
			
			/*处理权限组*/
			if(user.getGroupIds() != null && !"".equals(user.getGroupIds())){
				String s = user.getGroupIds().replace("|0", "");
				s = s.replace("|1", "");
				groupUserDao.delete("delete sys_group_user a where a.userid='"+user.getUserid()+"' and a.pgid not in ("+s+")");
				String pridept = user.getGroupIds().replace(" ","");
				String[] pridepts = pridept.split(",");
				List<GroupUser> list = new ArrayList<GroupUser>();
				for(int i=0;i<pridepts.length;i++){
					GroupUser pu = new GroupUser();
					String pgid = pridepts[i].replace("|", ",").split(",")[0];
					pu.setPgid(new Long(pgid));
					pu.setUserid(user.getUserid());
					boolean res = groupUserDao.isUnique(pu, "pgid,userid");
					if(res){
						list.add(pu);
					}
				}
				groupUserDao.getHibernateTemplate().saveOrUpdateAll(list);
			}else{
				groupUserDao.delete("delete sys_group_user a where a.userid='"+user.getUserid()+"'");
			}
			return true;
		}
	}
	
	public LoginInfo login(String username,String password){
		MD5 md5 = new MD5();
		String md_pwd = md5.getMD5ofStr(password);
		SysUser user = new SysUser();
		user.setUsername(username);
		user.setPassword(md_pwd);
		SysUser sysuser = sysUserDao.getUnique(user, "username,password");
		if(sysuser != null){
			LoginInfo loginInfo = new LoginInfo();
			loginInfo.setDeptid(sysuser.getDeptid());
			loginInfo.setTopdeptid(sysuser.getDeptid());
			loginInfo.setDeptname(sysuser.getDeptname());
			loginInfo.setUserid(sysuser.getUserid());
			loginInfo.setUsername(sysuser.getUsername());
			loginInfo.setRealname(sysuser.getRealname());
			loginInfo.setPassword(sysuser.getPassword());
			loginInfo.setState(new Integer(sysuser.getState()));
			loginInfo.setCategory(sysuser.getCategory());
			loginInfo.setUserrole(sysuser.getUserrole());
			loginInfo.setIsSysAdmin(sysuser.getIsadmin());
			
			if(ObjectUtils.isNotEmpty(sysuser.getDeptid())){
				Dept dept = deptDao.getById(sysuser.getDeptid());
				if(dept != null){
					if(ObjectUtils.isNotEmpty(dept.getPid())){
						loginInfo.setTopdeptid(dept.getPid());
					}
				}
			}
			
			if("c4ca4238a0b923820dcc509a6f75849b".equals(sysuser.getPassword())){
				loginInfo.setIsinit(0);
			}else{
				loginInfo.setIsinit(1);
			}
			return loginInfo;
		}else{
			return null;
		}
	}
	/**
	 * 自动登录
	 * @param username
	 * @param password
	 * @param domain
	 * @return
	 */
	public LoginInfo autoLogin(String username, String password) {
		SysUser user = new SysUser();
		user.setUsername(username);
		user.setPassword(password);
		boolean mark = sysUserDao.isUnique(user, "username,password");
		if(mark){
			return null;
		}else{
			LoginInfo loginInfo = new LoginInfo();
			SysUser sysuser = sysUserDao.getUnique(user, "username,password");
			loginInfo.setUsername(sysuser.getUsername());
			loginInfo.setRealname(sysuser.getRealname());
			loginInfo.setPassword(sysuser.getPassword());
			loginInfo.setState(new Integer(sysuser.getState()));
			loginInfo.setCategory(sysuser.getCategory());
			
			return loginInfo;
		}
	}
	/**
	 * 启动用户
	 * @param username
	 */
	public void activeStartUser(Long userid){
		SysUser user = sysUserDao.getById(userid);
		user.setState("1");
		sysUserDao.update(user);
	}
	/**
	 * 禁用用户
	 * @param username
	 */
	public void activeDisableUser(Long userid){
		SysUser user = sysUserDao.getById(userid);
		user.setState("0");
		sysUserDao.update(user);
	}
	/**
	 * 修改当前密码
	 * @param username
	 * @param currPwd
	 * @param newPwd
	 * @return
	 */
	public boolean updatePassword(Long userid,String currPwd,String newPwd,SysUser u){
		SysUser user = sysUserDao.getById(userid);
		MD5 md5 = new MD5();
		String curr_pwd = md5.getMD5ofStr(currPwd);
		if(user.getPassword().equals(curr_pwd)){
			String new_pwd = md5.getMD5ofStr(newPwd);
			user.setPassword(new_pwd);
			user.setEmail(u.getEmail());
			user.setMemo(u.getMemo());
			sysUserDao.update(user);
			
			SysYg yg =sysYgDao.getById(user.getUsername());
			if(yg != null){
				yg.setTel(u.getTel());
				yg.setPhone(u.getPhone());
				yg.setEmail(u.getEmail());
				sysYgDao.update(yg);
			}
			
			return true;
		}else{
			return false;
		}
	}
	
	@Transactional(readOnly=true)
	public List<SysUser> selectOnlyUser(String realname) {
		return sysUserDao.selectOnlyUser(realname);
	}
	
	@Transactional(readOnly=true)
	public List<SysUser> selectUser(Long keyid,String realname) {
		return sysUserDao.selectUser(keyid,realname);
	}
	
	/**
	 * 根据部门树，递推循环来装载每个部门的用户列表
	 * @param td
	 */
	@Transactional(readOnly=true)
	public void loadDeptTreeUsers(TreeData td){
		List<SysUser> users = sysUserDao.findByDept(new Long(td.getId()));
		List<TreeData> tdUsers = TreeUtils.setUserDatas(users);
		for(TreeData child_td : td.getItem()){
			loadDeptTreeUsers(child_td);
		}
		td.getItem().addAll(tdUsers);
	}
	public List<SysUser> searchLeader(Long keyid, String realname, Integer orgType) {
		return sysUserDao.searchLeader(keyid,realname,orgType);
	}
	public boolean checkWsByDept(Long deptId) {
		return false;
	}
	

}
